<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="keyword"  content="">
    <link rel="shortcut icon" href="/img/favicon.ico">

    <title>
        
          webpack原理与实战 - 浩麟的博客
        
    </title>

    <link rel="canonical" href="https://wuhaolin.cn/2017/05/31/webpack原理与实战/">

    <!-- Bootstrap Core CSS -->
    
<link rel="stylesheet" href="/css/bootstrap.min.css">


    <!-- Custom CSS -->
    
<link rel="stylesheet" href="/css/hux-blog.min.css">


    <!-- Pygments Highlight CSS -->
    
<link rel="stylesheet" href="/css/highlight.css">


    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
<meta name="generator" content="Hexo 4.1.1"></head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">

<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">浩麟的博客</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/">Home</a>
                    </li>
                    <li>
                        <a href="https://github.com/gwuhaolin/blog/" target="_blank">订阅</a>
                    </li>

                    

                        
                    

                        
                        <li>
                            <a href="/about/">关于</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/archives/">归档</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/tags/">标签</a>
                        </li>
                        
                    

                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


<!-- Main Content -->

<!-- Image to hack wechat -->
<!-- <img src="https://wuhaolin.cn/img/icon_wechat.png" width="0" height="0"> -->
<!-- <img src="{{ site.baseurl }}/{% if page.header-img %}{{ page.header-img }}{% else %}{{ site.header-img }}{% endif %}" width="0" height="0"> -->

<!-- Post Header -->
<style type="text/css">
    header.intro-header{
        background-image: url('/img/bg.jpg')
    }
</style>
<header class="intro-header" >
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <div class="post-heading">
                    <div class="tags">
                        
                          <a class="tag" href="/tags/#webpack" title="webpack">webpack</a>
                        
                    </div>
                    <h1>webpack原理与实战</h1>
                    <h2 class="subheading"></h2>
                    <span class="meta">
                        Posted by 吴浩麟 on
                        2017-05-31
                    </span>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">
    <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

                <p><a href="http://webpack.wuhaolin.cn/" target="_blank" rel="noopener"><img src="http://ou8vcvyuy.bkt.clouddn.com/dive-into-webpack-for-blog.jpg" alt=""></a></p>
<p>webpack是一个js打包工具，不一个完整的前端构建工具。它的流行得益于模块化和单页应用的流行。webpack提供扩展机制，在庞大的社区支持下各种场景基本它都可找到解决方案。本文的目的是教会你用webpack解决实战中常见的问题。</p>
<h2 id="webpack原理"><a href="#webpack原理" class="headerlink" title="webpack原理"></a>webpack原理</h2><p>在深入实战前先要知道webpack的运行原理</p>
<h3 id="webpack核心概念"><a href="#webpack核心概念" class="headerlink" title="webpack核心概念"></a>webpack核心概念</h3><ul>
<li><code>entry</code> 一个可执行模块或库的入口文件。</li>
<li><code>chunk</code> 多个文件组成的一个代码块，例如把一个可执行模块和它所有依赖的模块组合和一个 <code>chunk</code> 这体现了webpack的打包机制。</li>
<li><code>loader</code> 文件转换器，例如把es6转换为es5，scss转换为css。</li>
<li><code>plugin</code> 插件，用于扩展webpack的功能，在webpack构建生命周期的节点上加入扩展hook为webpack加入功能。</li>
</ul>
<h3 id="webpack构建流程"><a href="#webpack构建流程" class="headerlink" title="webpack构建流程"></a>webpack构建流程</h3><p>从启动webpack构建到输出结果经历了一系列过程，它们是：</p>
<ol>
<li>解析webpack配置参数，合并从shell传入和<code>webpack.config.js</code>文件里配置的参数，生产最后的配置结果。</li>
<li>注册所有配置的插件，好让插件监听webpack构建生命周期的事件节点，以做出对应的反应。</li>
<li>从配置的<code>entry</code>入口文件开始解析文件构建AST语法树，找出每个文件所依赖的文件，递归下去。</li>
<li>在解析文件递归的过程中根据文件类型和loader配置找出合适的loader用来对文件进行转换。</li>
<li>递归完后得到每个文件的最终结果，根据<code>entry</code>配置生成代码块<code>chunk</code>。</li>
<li>输出所有<code>chunk</code>到文件系统。</li>
</ol>
<p>需要注意的是，在构建生命周期中有一系列插件在合适的时机做了合适的事情，比如<code>UglifyJsPlugin</code>会在loader转换递归完后对结果再使用<code>UglifyJs</code>压缩覆盖之前的结果。</p>
<h2 id="场景和方案"><a href="#场景和方案" class="headerlink" title="场景和方案"></a>场景和方案</h2><p>通过各种场景和对应的解决方案让你深入掌握webpack</p>
<h3 id="单页应用"><a href="#单页应用" class="headerlink" title="单页应用"></a>单页应用</h3><p><strong>demo <a href="https://github.com/gwuhaolin/redemo" target="_blank" rel="noopener">redemo</a></strong><br>一个单页应用需要配置一个<code>entry</code>指明执行入口，webpack会为<code>entry</code>生成一个包含这个入口所有依赖文件的<code>chunk</code>，但要让它在浏览器里跑起来还需要一个HTML文件来加载<code>chunk</code>生成的js文件，如果提取出了css还需要让HTML文件引入提取出的css。<a href="https://github.com/gwuhaolin/web-webpack-plugin" target="_blank" rel="noopener">web-webpack-plugin</a>里的<code>WebPlugin</code>可以自动的完成这些工作。</p>
<p>webpack配置文件<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> &#123; WebPlugin &#125; = <span class="built_in">require</span>(<span class="string">'web-webpack-plugin'</span>);</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  entry: &#123;</span><br><span class="line">    app: <span class="string">'./src/doc/index.js'</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">  plugins: [</span><br><span class="line">    <span class="comment">// 一个WebPlugin对应生成一个html文件</span></span><br><span class="line">    <span class="keyword">new</span> WebPlugin(&#123;</span><br><span class="line">      <span class="comment">//输出的html文件名称</span></span><br><span class="line">      filename: <span class="string">'index.html'</span>,</span><br><span class="line">      <span class="comment">//这个html依赖的`entry`</span></span><br><span class="line">      requires: [<span class="string">'app'</span>],</span><br><span class="line">    &#125;),</span><br><span class="line">  ],</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p><code>requires: [&#39;doc&#39;]</code>指明这个HTML依赖哪些<code>entry</code>，<code>entry</code>生成的js和css会自动注入到HTML里。<br>你还可以配置这些资源的注入方式，支持如下属性：</p>
<ul>
<li><code>_dist</code> 只有在生产环境下才引入该资源</li>
<li><code>_dev</code> 只有在开发环境下才引入该资源</li>
<li><code>_inline</code> 把该资源的内容潜入到html里</li>
<li><code>_ie</code> 只有IE浏览器才需要引入的资源</li>
</ul>
<p>要设置这些属性可以通过在js里配置<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> WebPlugin(&#123;</span><br><span class="line">    filename: <span class="string">'index.html'</span>,</span><br><span class="line">    requires: &#123;</span><br><span class="line">         app:&#123;</span><br><span class="line">              _dist:<span class="literal">true</span>,</span><br><span class="line">              _inline:<span class="literal">false</span>,</span><br><span class="line">         &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;),</span><br></pre></td></tr></table></figure></p>
<p>或者在模版里设置，使用模版的好处是灵活的控制资源注入点。<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> WebPlugin(&#123;</span><br><span class="line">      filename: <span class="string">'index.html'</span>,</span><br><span class="line">      template: <span class="string">'./template.html'</span>,</span><br><span class="line">&#125;),</span><br></pre></td></tr></table></figure></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"zh-cn"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"stylesheet"</span> <span class="attr">href</span>=<span class="string">"app?_inline"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"ie-polyfill?_ie"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"react-body"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"app"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><code>WebPlugin</code>插件借鉴了<code>fis3</code>的思想，补足了webpack缺失的以HTML为入口的功能。想了解<code>WebPlugin</code>的更多功能，见<a href="https://github.com/gwuhaolin/web-webpack-plugin/blob/master/readme_zh.md#输出html文件-demo" target="_blank" rel="noopener">文档</a>。</p>
<h3 id="一个项目里管理多个单页应用"><a href="#一个项目里管理多个单页应用" class="headerlink" title="一个项目里管理多个单页应用"></a>一个项目里管理多个单页应用</h3><p>一般项目里会包含多个单页应用，虽然多个单页应用也可以合并成一个但是这样做会导致用户没访问的部分也加载了。如果项目里有很多个单页应用，为每个单页应用配置一个<code>entry</code>和<code>WebPlugin</code>？如果项目又新增了一个单页应用，又去新增webpack配置？这样做太麻烦了，<a href="https://github.com/gwuhaolin/web-webpack-plugin" target="_blank" rel="noopener">web-webpack-plugin</a>里的<code>AutoWebPlugin</code>可以方便的解决这些问题。<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    plugins: [</span><br><span class="line">        <span class="comment">// 所有页面的入口目录</span></span><br><span class="line">        <span class="keyword">new</span> AutoWebPlugin(<span class="string">'./src/'</span>),</span><br><span class="line">    ]</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p><code>AutoWebPlugin</code>会把<code>./src/</code>目录下所有每个文件夹作为一个单页页面的入口，自动为所有的页面入口配置一个WebPlugin输出对应的html。要新增一个页面就在<code>./src/</code>下新建一个文件夹包含这个单页应用所依赖的代码，<code>AutoWebPlugin</code>自动生成一个名叫文件夹名称的html文件。<code>AutoWebPlugin</code>的更多功能见<a href="https://github.com/gwuhaolin/web-webpack-plugin/blob/master/readme_zh.md#自动探测html入口-demo" target="_blank" rel="noopener">文档</a>。</p>
<h3 id="代码分割优化"><a href="#代码分割优化" class="headerlink" title="代码分割优化"></a>代码分割优化</h3><p>一个好的代码分割对浏览器首屏效果提升很大。比如对于最常见的react体系你可以</p>
<ol>
<li>先抽出基础库<code>react</code> <code>react-dom</code> <code>redux</code> <code>react-redux</code>到一个单独的文件而不是和其它文件放在一起打包为一个文件，这样做的好处是只要你不升级他们的版本这个文件永远不会被刷新。如果你把这些基础库和业务代码打包在一个文件里每次改动业务代码都会导致文件hash值变化从而导致缓存失效浏览器重复下载这些包含基础库的代码。以上的配置为：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// vender.js 文件抽离基础库到单独的一个文件里防止跟随业务代码被刷新</span></span><br><span class="line"><span class="comment">// 所有页面都依赖的第三方库</span></span><br><span class="line"><span class="comment">// react基础</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="string">'react-dom'</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="string">'react-redux'</span>;</span><br><span class="line"><span class="comment">// redux基础</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">'redux'</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="string">'redux-thunk'</span>;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// webpack配置</span></span><br><span class="line">&#123;</span><br><span class="line">  entry: &#123;</span><br><span class="line">    vendor: <span class="string">'./path/to/vendor.js'</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li>再通过<a href="https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin" target="_blank" rel="noopener">CommonsChunkPlugin</a>可以提取出多个代码块都依赖的代码形成一个单独的<code>chunk</code>。在应用有多个页面的场景下提取出所有页面公共的代码减少单个页面的代码，在不同页面之间切换时所有页面公共的代码之前被加载过而不必重新加载。</li>
</ol>
<h3 id="构建npm包"><a href="#构建npm包" class="headerlink" title="构建npm包"></a>构建npm包</h3><p><strong>demo <a href="https://github.com/gwuhaolin/remd" target="_blank" rel="noopener">remd</a></strong><br>除了构建可运行的web应用，webpack也可用来构建发布到npm上去的给别人调用的js库。<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nodeExternals = <span class="built_in">require</span>(<span class="string">'webpack-node-externals'</span>);</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  entry: &#123;</span><br><span class="line">    index: <span class="string">'./src/index.js'</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">  externals: [nodeExternals()],</span><br><span class="line">  target: <span class="string">'node'</span>,</span><br><span class="line">  output: &#123;</span><br><span class="line">    path: path.resolve(__dirname, <span class="string">'.npm'</span>),</span><br><span class="line">    filename: <span class="string">'[name].js'</span>,</span><br><span class="line">    libraryTarget: <span class="string">'commonjs2'</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>这里有几个区别于web应用不同的地方：</p>
<ul>
<li><code>externals: [nodeExternals()]</code>用于排除<code>node_modules</code>目录下的代码被打包进去，因为放在<code>node_modules</code>目录下的代码应该通过npm安装。</li>
<li><code>libraryTarget: &#39;commonjs2&#39;</code>指出<code>entry</code>是一个可供别人调用的库而不是可执行的，输出的js文件按照commonjs规范。</li>
</ul>
<h3 id="构建服务端渲染"><a href="#构建服务端渲染" class="headerlink" title="构建服务端渲染"></a>构建服务端渲染</h3><p>服务端渲染的代码要运行在nodejs环境，和浏览器不同的是，服务端渲染代码需要采用commonjs规范同时不应该包含除js之外的文件比如css。webpack配置如下：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  target: <span class="string">'node'</span>,</span><br><span class="line">  entry: &#123;</span><br><span class="line">    <span class="string">'server_render'</span>: <span class="string">'./src/server_render'</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">  output: &#123;</span><br><span class="line">    filename: <span class="string">'./dist/server/[name].js'</span>,</span><br><span class="line">    libraryTarget: <span class="string">'commonjs2'</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="built_in">module</span>: &#123;</span><br><span class="line">    rules: [</span><br><span class="line">      &#123;</span><br><span class="line">        test: <span class="regexp">/\.js$/</span>,</span><br><span class="line">        loader: <span class="string">'babel-loader'</span>,</span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        test: <span class="regexp">/\.(scss|css|pdf)$/</span>,</span><br><span class="line">        loader: <span class="string">'ignore-loader'</span>,</span><br><span class="line">      &#125;,</span><br><span class="line">    ]</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>其中几个关键的地方在于：</p>
<ul>
<li><code>target: &#39;node&#39;</code> 指明构建出的代码是要运行在node环境里</li>
<li><code>libraryTarget: &#39;commonjs2&#39;</code> 指明输出的代码要是commonjs规范</li>
<li><code>{test: /\.(scss|css|pdf)$/,loader: &#39;ignore-loader&#39;}</code> 是为了防止不能在node里执行服务端渲染也用不上的文件被打包进去。</li>
</ul>
<h3 id="从fis3迁移到webpack"><a href="#从fis3迁移到webpack" class="headerlink" title="从fis3迁移到webpack"></a>从fis3迁移到webpack</h3><p>fis3和webpack有相似的地方也有不同的地方。相似在于他们都采用commonjs规范，不同在于导入css这些非js资源的方式。fis3通过<code>// @require &#39;./index.scss&#39;</code>而webpack通过<code>require(&#39;./index.scss&#39;)</code>。如果想从fis3平滑迁移到webpack可以使用<a href="https://github.com/gwuhaolin/comment-require-loader/issues" target="_blank" rel="noopener">comment-require-loader</a>。比如你想在webpack构建是使用采用了fis3方式的<code>imui</code>模块，配置如下：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">loaders:[&#123;</span><br><span class="line">     test: <span class="regexp">/\.js$/</span>,</span><br><span class="line">     loaders: [<span class="string">'comment-require-loader'</span>],</span><br><span class="line">     include: [path.resolve(__dirname, <span class="string">'node_modules/imui'</span>),]</span><br><span class="line">&#125;]</span><br></pre></td></tr></table></figure></p>
<h2 id="自定义webpack扩展"><a href="#自定义webpack扩展" class="headerlink" title="自定义webpack扩展"></a>自定义webpack扩展</h2><p>如果你在社区找不到你的应用场景的解决方案，那就需要自己动手了写loader或者plugin了。<br>在你编写自定义webpack扩展前你需要想明白到底是要做一个<code>loader</code>还是<code>plugin</code>呢？可以这样判断：</p>
<blockquote>
<p>如果你的扩展是想对一个个单独的文件进行转换那么就编写<code>loader</code>剩下的都是<code>plugin</code>。</p>
</blockquote>
<p>其中对文件进行转换可以是像：</p>
<ul>
<li><code>babel-loader</code>把es6转换成<code>es5</code></li>
<li><code>file-loader</code>把文件替换成对应的URL</li>
<li><code>raw-loader</code>注入文本文件内容到代码里去</li>
</ul>
<h3 id="编写-webpack-loader"><a href="#编写-webpack-loader" class="headerlink" title="编写 webpack loader"></a>编写 webpack loader</h3><p><strong>demo <a href="https://github.com/gwuhaolin/comment-require-loader" target="_blank" rel="noopener">comment-require-loader</a></strong><br>编写<code>loader</code>非常简单，以comment-require-loader为例：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span> (<span class="params">content</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> replace(content);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p><code>loader</code>的入口需要导出一个函数，这个函数要干的事情就是转换一个文件的内容。<br>函数接收的参数<code>content</code>是一个文件在转换前的字符串形式内容，需要返回一个新的字符串形式内容作为转换后的结果，所有通过模块化倒入的文件都会经过<code>loader</code>。从这里可以看出<code>loader</code>只能处理一个个单独的文件而不能处理代码块。想编写更复杂的loader可参考<a href="https://webpack.github.io/docs/loaders.html" target="_blank" rel="noopener">官方文档</a></p>
<h3 id="编写-webpack-plugin"><a href="#编写-webpack-plugin" class="headerlink" title="编写 webpack plugin"></a>编写 webpack plugin</h3><p><strong>demo <a href="https://github.com/gwuhaolin/end-webpack-plugin" target="_blank" rel="noopener">end-webpack-plugin</a></strong><br><code>plugin</code>应用场景广泛，所以稍微复杂点。以end-webpack-plugin为例：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">EndWebpackPlugin</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">constructor</span>(doneCallback, failCallback) &#123;</span><br><span class="line">        <span class="keyword">this</span>.doneCallback = doneCallback;</span><br><span class="line">        <span class="keyword">this</span>.failCallback = failCallback;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    apply(compiler) &#123;</span><br><span class="line">        <span class="comment">// 监听webpack生命周期里的事件，做相应的处理</span></span><br><span class="line">        compiler.plugin(<span class="string">'done'</span>, (stats) =&gt; &#123;</span><br><span class="line">            <span class="keyword">this</span>.doneCallback(stats);</span><br><span class="line">        &#125;);</span><br><span class="line">        compiler.plugin(<span class="string">'failed'</span>, (err) =&gt; &#123;</span><br><span class="line">            <span class="keyword">this</span>.failCallback(err);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = EndWebpackPlugin;</span><br></pre></td></tr></table></figure></p>
<p><code>loader</code>的入口需要导出一个class, 在<code>new EndWebpackPlugin()</code>的时候通过构造函数传入这个插件需要的参数，在webpack启动的时候会先实例化<code>plugin</code>再调用<code>plugin</code>的<code>apply</code>方法，插件需要在<code>apply</code>函数里监听webpack生命周期里的事件，做相应的处理。<br>webpack plugin 里有2个核心概念：</p>
<ul>
<li><code>Compiler</code>: 从webpack启动到推出只存在一个<code>Compiler</code>，<code>Compiler</code>存放着webpack配置</li>
<li><code>Compilation</code>: 由于webpack的监听文件变化自动编译机制，<code>Compilation</code>代表一次编译。</li>
</ul>
<p><code>Compiler</code> 和 <code>Compilation</code> 都会广播一系列事件。<br>webpack生命周期里有非常多的事件可以在<a href="https://webpack.js.org/api/plugins/compiler/#event-hooks" target="_blank" rel="noopener">event-hooks</a>和<a href="https://webpack.js.org/api/plugins/compilation/" target="_blank" rel="noopener">Compilation</a>里查到。以上只是一个最简单的demo，更复杂的可以查看 <a href="https://github.com/webpack/docs/wiki/how-to-write-a-plugin" target="_blank" rel="noopener">how to write a plugin</a>或参考<a href="https://github.com/gwuhaolin/web-webpack-plugin" target="_blank" rel="noopener">web-webpack-plugin</a>。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>webpack其实很简单，可以用一句话涵盖它的本质：</p>
<blockquote>
<p>webpack是一个打包模块化js的工具，可以通过loader转换文件，通过plugin扩展功能。</p>
</blockquote>
<p>如果webpack让你感到复杂，一定是各种loader和plugin的原因。<br>希望本文能让你明白webpack的原理与本质让你可以在实战中灵活应用webpack。</p>
<p><a href="http://wuhaolin.cn/2017/05/31/webpack%E5%8E%9F%E7%90%86%E4%B8%8E%E5%AE%9E%E6%88%98/">阅读原文</a></p>


                <hr>

                 <strong><a href="https://github.com/gwuhaolin/blog/issues/4" target="_blank" rel="noopener">在Github上参与本文讨论</a></strong>

                <ul class="pager">
                    
                        <li class="previous">
                            <a href="/2017/06/02/音视频技术参考资料/" data-toggle="tooltip" data-placement="top" title="音视频技术参考资料">&larr; Previous Post</a>
                        </li>
                    
                    
                        <li class="next">
                            <a href="/2017/05/17/使用flv.js做直播/" data-toggle="tooltip" data-placement="top" title="使用flv.js做直播">Next Post &rarr;</a>
                        </li>
                    
                </ul>
            </div>
    <!-- Side Catalog Container -->
        

    <!-- Sidebar Container -->

            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/tags/">FEATURED TAGS</a></h5>
                    <div class="tags">
                       
                          <a class="tag" href="/tags/#webpack" title="webpack">webpack</a>
                        
                    </div>
                </section>
                

                <!-- Friends Blog -->
                
            </div>

        </div>
    </div>
</article>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script>
    async("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js",function(){
        anchors.options = {
          visible: 'always',
          placement: 'right',
          icon: '#'
        };
        anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
    })
</script>
<style>
    /* place left on bigger screen */
    @media all and (min-width: 800px) {
        .anchorjs-link{
            position: absolute;
            left: -0.75em;
            font-size: 1.1em;
            margin-top : -0.1em;
        }
    }
</style>



<!-- Footer -->
<!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <ul class="list-inline text-center">
                    
                    
                    
                    <li>
                        <a target="_blank" href="https://www.zhihu.com/people/wu-hao-lin-67-15">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa  fa-stack-1x fa-inverse">知</i>
                            </span>
                        </a>
                    </li>
                    

                    

                    

                    
                    <li>
                        <a target="_blank" href="https://github.com/gwuhaolin">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-github fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                    

                    

                </ul>
                <p class="copyright text-muted">
                    Copyright &copy; 浩麟的博客 2019
                    <br>
                    Ported by <a href="https://github.com/gwuhaolin" target="_blank" rel="noopener">gwuhaolin</a> |
                    订阅本站<iframe
                            style="margin-left: 2px; margin-bottom:-5px;"
                            frameborder="0" scrolling="0" width="91px" height="20px"
                            src="https://ghbtns.com/github-btn.html?user=gwuhaolin&repo=blog&type=star&count=true">
                    </iframe>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->

<script src="/js/jquery.min.js"></script>


<!-- Bootstrap Core JavaScript -->

<script src="/js/bootstrap.min.js"></script>


<!-- Custom Theme JavaScript -->

<script src="/js/hux-blog.min.js"></script>



<!-- async load function -->
<script>
    function async(u, c) {
        var d = document, t = 'script',
            o = d.createElement(t),
            s = d.getElementsByTagName(t)[0];
        o.src = u;
        if (c) {
            o.addEventListener('load', function (e) {
                c(null, e);
            }, false);
        }
        s.parentNode.insertBefore(o, s);
    }
</script>


<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if ($('#tag_cloud').length !== 0) {
        async("https://wuhaolin.cn/js/jquery.tagcloud.js", function () {
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function () {
        var $nav = document.querySelector("nav");
        if ($nav) FastClick.attach($nav);
    })
</script>


<!-- Google Analytics -->


<script>
    // dynamic User by Hux
    var _gaId = 'UA-54964850-1';
    var _gaDomain = 'wuhaolin.cn';

    // Originial
    (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r;
        i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date();
        a = s.createElement(o),
            m = s.getElementsByTagName(o)[0];
        a.async = 1;
        a.src = g;
        m.parentNode.insertBefore(a, m)
    })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

    ga('create', _gaId, _gaDomain);
    ga('send', 'pageview');
</script>




<!-- Side Catalog -->


<!--Google Auto AD-->
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
    (adsbygoogle = window.adsbygoogle || []).push({
        google_ad_client: "ca-pub-9697944574373240",
        enable_page_level_ads: true
    });
</script>



<!-- Image to hack wechat -->
<img src="https://wuhaolin.cn /img/icon_wechat.png" width="0" height="0"/>
<!-- Migrate from head to bottom, no longer block render and still work -->
</body>

</html>
